package com.ruoyi.deepSeek;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.analyse.domain.ChatMessage;
import com.ruoyi.analyse.service.IChatMessageService;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.controller.DsXxController;
import com.ruoyi.system.domain.DsLt;
import com.ruoyi.system.domain.DsXx;
import com.ruoyi.system.service.IDsLtService;
import com.ruoyi.system.service.IDsXxService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class HttpClient {

    @Autowired
    private IDsXxService dsXxService;  // 将dsXxService从静态成员变量变为实例变量
    private static IDsXxService staticDsXxService;

    @Autowired
    private IDsLtService dsLtService;
    private static IDsLtService staticDsLtService;

    @PostConstruct
    public void init() {
        staticDsXxService = dsXxService;  // 将注入的dsXxService赋值给静态成员变量
        staticDsLtService = dsLtService;  // 将注入的dsLtService赋值给静态成员变量
    }
    private static final String API_URL = "http://127.0.0.1:88/v1"; // 基础 URL
    private static final String API_KEY = "app-aGOJgu4cN0NP4srUVOToGMTi"; // 替换为实际 API Key
    private static final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(100, TimeUnit.SECONDS)  // 连接超时设置为 100 秒
        .readTimeout(100, TimeUnit.SECONDS)     // 读取超时设置为 100 秒
        .writeTimeout(100, TimeUnit.SECONDS)    // 写入超时设置为 100 秒
        .build();

    public static SseEmitter postChatMessageStream(String user, String query, String conversationId, String responseMode, Long classId) {
        // 构建请求体
        StringBuilder jsonBodyBuilder = new StringBuilder();
        jsonBodyBuilder.append("{");
        if (query != null && !query.isEmpty()) {
            jsonBodyBuilder.append("\"query\": \"").append(query.replace("\"", "\\\"")).append("\",");
        }
        if (user != null && !user.isEmpty()) {
            jsonBodyBuilder.append("\"user\": \"").append(user).append("\",");
        }
        if (responseMode != null && !responseMode.isEmpty()) {
            jsonBodyBuilder.append("\"response_mode\": \"").append(responseMode).append("\",");
        }
        if (conversationId != null && !conversationId.isEmpty()) {
            jsonBodyBuilder.append("\"conversation_id\": \"").append(conversationId).append("\",");
        }
        jsonBodyBuilder.append("\"inputs\": {}}");

        String jsonData = jsonBodyBuilder.toString();
        System.out.println("发送请求: " + jsonData);

        // 首先保存用户的提问到DsXx表
        DsXx userMessage = new DsXx();
        userMessage.setXxContent(query);
        userMessage.setLtId(conversationId);
        userMessage.setUserName(user);
        userMessage.setClassId(classId);
        userMessage.setRole("user");
        userMessage.setCreateTime(new Date());
//    staticDsXxService.insertDsXx(userMessage);

        // 调用问题分析服务
        try {
            // 转换为ChatMessage对象以便分析
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setXxContent(query);
            chatMessage.setLtId(conversationId);
            chatMessage.setUserName(user);
            chatMessage.setRole("user");
            chatMessage.setClassId(classId);
            chatMessage.setClassId(userMessage.getClassId());
            chatMessage.setCreateTime(new Date());

            // 获取分析服务的Spring Bean实例
            IChatMessageService chatMessageService = SpringUtils.getBean(IChatMessageService.class);

            // 调用分析方法，这将触发关键词提取、学科分类、复杂度评估等
            chatMessageService.processAndAnalyzeQuestion(chatMessage);
        } catch (Exception e) {
            System.err.println("分析问题时发生错误: " + e.getMessage());
            e.printStackTrace();
            // 这里不会阻止正常的AI响应流程，只是记录错误
        }

        // 构建请求
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonData);

        Request request = new Request.Builder()
            .url(API_URL + "/chat-messages")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .header("Accept", "text/event-stream")
            .post(body)
            .build();

        // 创建SseEmitter实例，0L表示不超时
        SseEmitter emitter = new SseEmitter(0L);
        System.out.println("创建SseEmitter实例");

        // 在新线程中执行请求，避免阻塞
        new Thread(() -> {
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    System.out.println("请求失败: " + response.code());
                    emitter.completeWithError(new Exception("API请求失败: " + response.code()));
                    return;
                }
                System.out.println("请求成功");

                if (response.body() != null) {
                    try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.body().byteStream()))) {
                        String line;
                        StringBuilder eventBuilder = new StringBuilder();
                        String eventName = null;
                        String lineLastOne = "";
                        while ((line = reader.readLine()) != null) {
                            System.out.println("接收到行: " + line);
                            if (!line.startsWith("event:") && !line.isEmpty()) {
                                String lineBeUse = line.substring(5);
                                JSONObject jsonObject = JSONObject.parseObject(lineBeUse);
                                System.out.println("接收到行jsonObject: " + jsonObject);

                                // 如果是 workflow_finished 事件，保存 AI 回复内容
                                if ("workflow_finished".equals(jsonObject.getString("event"))) {
                                    String answer = jsonObject.getJSONObject("data").getJSONObject("outputs").getString("answer");
                                    if (answer != null) {
                                        // 直接保存 workflow_finished 的内容
                                        System.out.println("【调试】收到workflow_finished事件");
                                        DsXx aiResponseMessage = new DsXx();
                                        aiResponseMessage.setXxContent(answer); // 使用 workflow_finished 中的 answer
                                        aiResponseMessage.setLtId(jsonObject.getString("conversation_id"));
                                        aiResponseMessage.setRole("AI");
                                        aiResponseMessage.setUserName(user);
                                        aiResponseMessage.setClassId(classId);
                                        aiResponseMessage.setCreateTime(new Date());
                                        staticDsXxService.insertDsXx(aiResponseMessage); // 保存到数据库
                                        System.out.println("插入AI回复到消息表");
                                    }
                                }

                                // 如果是 message_end 事件，保存用户提问
                                if ("message_end".equals(jsonObject.getString("event"))) {
                                    System.out.println("插入会话记录");
                                    // 插入用户提问到消息表
                                    userMessage.setLtId(jsonObject.getString("conversation_id"));
                                    staticDsXxService.insertDsXx(userMessage);

                                    // 插入会话记录
                                    DsLt dsLt = new DsLt();
                                    dsLt.setConversationId(jsonObject.getString("conversation_id"));
                                    dsLt.setUserName(user);
                                    List<DsLt> dsLts = staticDsLtService.selectDsLtList(dsLt);
                                    dsLt.setLtTitle(jsonObject.getString("thought")); // 检查 thought 是否存在
                                    dsLt.setClassId(classId);
                                    dsLt.setCreateTime(new Date());
                                    if (dsLts.isEmpty()) {
                                        staticDsLtService.insertDsLt(dsLt);
                                    }
                                }
                                lineLastOne = lineBeUse;
                            }
                            if (line.isEmpty()) {
                                // 空行表示一个事件的结束
                                if (eventBuilder.length() > 0) {
                                    String eventData = eventBuilder.toString();
                                    // 发送事件到前端
                                    if (eventName != null) {
                                        emitter.send(SseEmitter.event().name(eventName).data(eventData));
                                    } else {
                                        emitter.send(eventData);
                                    }
                                    // 重置缓冲区
                                    eventBuilder.setLength(0);
                                    eventName = null;
                                }
                            } else if (line.startsWith("event:")) {
                                // 提取事件名称
                                eventName = line.substring(6).trim();
                            } else if (line.startsWith("data:")) {
                                // 提取事件数据
                                eventBuilder.append(line.substring(5).trim());
                            }
                        }
                        // 处理最后一个可能的事件
                        if (eventBuilder.length() >= 0) {
                            String eventData = eventBuilder.toString();
                            if (eventName != null) {
                                emitter.send(SseEmitter.event().name(eventName).data(eventData));
                            } else {
                                emitter.send(eventData);
                            }
                        }
                    }
                }

                // 完成发射器
                emitter.complete();

            } catch (IOException e) {
                System.err.println("流式传输错误: " + e.getMessage());
                e.printStackTrace();
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }




    // 处理流式消息并传输给前端
//    public static void postChatMessageStream(String user, String query, String conversationId, String responseMode, OutputStream outputStream) throws IOException {
//        // 构建请求体
//        MediaType mediaType = MediaType.parse("application/json");
//        StringBuilder jsonBodyBuilder = new StringBuilder();
//        jsonBodyBuilder.append("{");
//        if (query != null && !query.isEmpty()) {
//            jsonBodyBuilder.append("\"query\": \"").append(query).append("\",");
//        }
//        if (user != null && !user.isEmpty()) {
//            jsonBodyBuilder.append("\"user\": \"").append(user).append("\",");
//        }
//        if (responseMode != null && !responseMode.isEmpty()) {
//            jsonBodyBuilder.append("\"response_mode\": \"").append(responseMode).append("\",");
//        }
//        if (conversationId != null && !conversationId.isEmpty()) {
//            jsonBodyBuilder.append("\"conversation_id\": \"").append(conversationId).append("\",");
//        }
//        jsonBodyBuilder.append("\"inputs\": {}}");
//
//        String jsonBody = jsonBodyBuilder.toString();
//        RequestBody body = RequestBody.create(mediaType, jsonBody);
//        System.out.println("Sending request: " + jsonBody);
//
//        Request request = new Request.Builder()
//            .url(API_URL + "/chat-messages")
//            .header("Authorization", "Bearer " + API_KEY)
//            .header("Content-Type", "application/json")
//            .header("Accept-Encoding", "identity")
//            .post(body)
//            .build();
//        System.out.println(request.toString());
//        try (Response response = client.newCall(request).execute()) {
//            System.out.println(response);
//            if (response.body() != null) {
//                // 获取API的响应流，并逐块转发到前端
//                InputStream inputStream = response.body().byteStream();
//
//                byte[] buffer = new byte[1024]; // 缓冲区用于读取响应数据
//                int bytesRead;
//
//                // 实时将数据流写入到前端输出流
//                while ((bytesRead = inputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                    outputStream.flush();  // 每次写入后立即刷新
//                }
//            }
//        } catch (IOException e) {
//            System.err.println("Error in streaming: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }

    /*已弃用
    * 这种方式在api返回数据后会先使用 response.body().string()
    * 读取整个响应内容并在内存中构建响应数据，再发送给前端
    * 响应与请求的处理是阻塞式的，会在所有数据接收到后才进行转发
    * */
    // 处理流式消息并原封不动传输给前端
//    public static void postChatMessageStream(String user, String query, String conversationId, String responseMode, OutputStream outputStream) throws IOException {
//        // 构建请求体
//        MediaType mediaType = MediaType.parse("application/json");
//        StringBuilder jsonBodyBuilder = new StringBuilder();
//        jsonBodyBuilder.append("{");
//
//        if (query != null && !query.isEmpty()) {
//            jsonBodyBuilder.append("\"query\": \"").append(query).append("\",");
//        }
//
//        if (user != null && !user.isEmpty()) {
//            jsonBodyBuilder.append("\"user\": \"").append(user).append("\",");
//        }
//
//        if (responseMode != null && !responseMode.isEmpty()) {
//            jsonBodyBuilder.append("\"response_mode\": \"").append(responseMode).append("\",");
//        }
//
//        if (conversationId != null && !conversationId.isEmpty()) {
//            jsonBodyBuilder.append("\"conversation_id\": \"").append(conversationId).append("\",");
//        }
//
////        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
////            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
////        }
//
//        jsonBodyBuilder.append("\"inputs\": {}}");
//
//        String jsonBody = jsonBodyBuilder.toString();
//        RequestBody body = RequestBody.create(mediaType, jsonBody);
//        System.out.println("Sending request: " + jsonBody);
//
//        Request request = new Request.Builder()
//            .url(API_URL + "/chat-messages")
//            .header("Authorization", "Bearer " + API_KEY)
//            .header("Content-Type", "application/json")
//            .post(body)
//            .build();
//
//        try (Response response = client.newCall(request).execute()) {
//            if (response.body() != null) {
//                String responseString = response.body().string();
//                String[] chunks = responseString.split("\n\n");
//
//                // 打印日志查看数据是否到达
//                System.out.println("Received response: " + responseString);
//
//                // 逐块传输数据
//                for (String chunk : chunks) {
//                    if (chunk.startsWith("data: ")) {
//                        String data = chunk.substring(6).trim(); // 去掉前缀 'data: '
//                        if (!data.isEmpty()) {
//                            // 打印发送的数据
//                            System.out.println("Sending data: " + data);
//
//                            // 立即将数据发送给前端并确保刷新
//                            outputStream.write(("data: " + data + "\n\n").getBytes());
//
//                            // 打印发送的时间戳
//                            System.out.println("TIME: " + System.currentTimeMillis());
//
//                            // 立即调用 flush() 确保数据实时发送到前端
//                            outputStream.flush();
//                        }
//                    }
//                }
//
//            }
//        } catch (IOException e) {
//            System.err.println("Error in streaming: " + e.getMessage()); // 打印错误日志
//            e.printStackTrace();
//        }
//    }

    // 文件上传处理
    public static String uploadFile(String user, String filePath) throws IOException {
        MediaType mediaType = MediaType.parse("image/*");
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(mediaType, file);
        MultipartBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(), fileBody)
            .addFormDataPart("user", user)
            .build();

        Request request = new Request.Builder()
            .url(API_URL + "/files/upload")
            .header("Authorization", "Bearer " + API_KEY)
            .post(requestBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string(); // 返回文件上传响应
        }
    }

    // 获取会话历史消息
    public static String getMessages(String user, String conversationId, String firstId, int limit) throws IOException {
        // 构建URL并根据参数添加查询参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_URL + "/messages").newBuilder();

        if (user != null && !user.isEmpty()) {
            urlBuilder.addQueryParameter("user", user);
        }

        if (conversationId != null && !conversationId.isEmpty()) {
            urlBuilder.addQueryParameter("conversation_id", conversationId);
        }

        if (firstId != null && !firstId.isEmpty()) {
            urlBuilder.addQueryParameter("first_id", firstId);
        }

        if (limit > 0) {
            urlBuilder.addQueryParameter("limit", String.valueOf(limit));
        }

        HttpUrl url = urlBuilder.build();

        // 构建请求
        Request request = new Request.Builder()
            .url(url)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


    // 获取会话列表
    public static String getConversations(String user, String lastId, int limit) throws IOException {
        // 构建URL并根据参数添加查询参数
        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_URL + "/conversations").newBuilder();

        if (user != null && !user.isEmpty()) {
            urlBuilder.addQueryParameter("user", user);
        }

        if (lastId != null && !lastId.isEmpty()) {
            urlBuilder.addQueryParameter("last_id", lastId);
        }

        if (limit > 0) {
            urlBuilder.addQueryParameter("limit", String.valueOf(limit));
        }

        HttpUrl url = urlBuilder.build();

        // 构建请求
        Request request = new Request.Builder()
            .url(url)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("response: " + response);
            return response.body().string();
        }
    }


    // 删除会话
    public static String deleteConversation(String conversationId, String user) throws IOException {
        // 构建请求体，只有当参数不为空时才加入
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        // 如果 user 不为空，添加到请求体中
        if (user != null && !user.isEmpty()) {
            jsonBodyBuilder.append("\"user\": \"").append(user).append("\"");
        }
        // 确保没有多余的逗号
        jsonBodyBuilder.append("}");
        // 构建 JSON 请求体
        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);
        Request request = new Request.Builder()
            .url(API_URL + "/conversations/" + conversationId)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .delete(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }



    // 会话重命名
    public static String renameConversation(String conversationId, String user, String newName, boolean autoGenerate) throws IOException {
        // 构建请求体，只有当参数不为空时才加入
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (newName != null && !newName.isEmpty()) {
            jsonBodyBuilder.append("\"name\": \"").append(newName).append("\",");
        }

        jsonBodyBuilder.append("\"auto_generate\": ").append(autoGenerate);

        if (user != null && !user.isEmpty()) {
            jsonBodyBuilder.append(",\"user\": \"").append(user).append("\"");
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        System.out.println("jsonBody: " + jsonBody);
        Request request = new Request.Builder()
            .url(API_URL + "/conversations/" + conversationId + "/name")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


    // 语音转文字
    public static String audioToText(String user, String filePath) throws IOException {
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("audio/*"), file);
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(), fileBody);

        if (user != null && !user.isEmpty()) {
            requestBodyBuilder.addFormDataPart("user", user);
        }

        MultipartBody requestBody = requestBodyBuilder.build();

        Request request = new Request.Builder()
            .url(API_URL + "/audio-to-text")
            .header("Authorization", "Bearer " + API_KEY)
            .post(requestBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


    // 文字转语音
    public static String textToAudio(String user, String text) throws IOException {
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("text", text);

        if (user != null && !user.isEmpty()) {
            requestBodyBuilder.addFormDataPart("user", user);
        }

        MultipartBody requestBody = requestBodyBuilder.build();

        Request request = new Request.Builder()
            .url(API_URL + "/text-to-audio")
            .header("Authorization", "Bearer " + API_KEY)
            .post(requestBody)
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}
